package com.youth.framework.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.StringUtils;

import com.youth.framework.authority.entity.Resources;
import com.youth.framework.authority.entity.Role;
import com.youth.platform.dao.SystemDao;

public class MyUserDetailServiceImpl implements UserDetailsService {

	@Resource(name = "systemDao")
	private SystemDao systemDao;

	// 登录验证
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		com.youth.platform.entity.User user = null;
		try {
			com.youth.platform.entity.User usertemp = new com.youth.platform.entity.User();
			usertemp.setUserName(username);
			user = systemDao.queryUsersInfo(usertemp);
		} catch (Exception e) {
			// 记录日志
		}
		if (user == null) {
			throw new UsernameNotFoundException(username);
		}
		Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(user);

		boolean enables = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;

		User userdetail = new User(user.getUserName(), user.getUserPassword(),
				enables, accountNonExpired, credentialsNonExpired,
				accountNonLocked, grantedAuths); // 用户的权限
		return userdetail;
	}

	// 取得用户的权限
	private Set<GrantedAuthority> obtionGrantedAuthorities(
			com.youth.platform.entity.User user) {
		List<Resources> resources = new ArrayList<Resources>();
		List<Role> roles = user.getRoles();
		for (Role role : roles) {
			if (!StringUtils.isEmpty(role.getRoleName())) {
				List<Resources> tempRes = role.getResources();

				for (Resources res : tempRes) {
					if (!StringUtils.isEmpty(res.getResourceName())) {
						resources.add(res);
					}
				}
			}
		}

		Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
		for (Resources res : resources) {
			authSet.add(new SimpleGrantedAuthority("ROLE_"
					+ res.getResourceName()));
		}
		return authSet;
	}
}
